const BaseRest = require('./base.js');

module.exports = class extends BaseRest {
  async getAction() {
    let data = {};
    const map = {};
    // 获取详情
    if (this.id) {
      map.id = this.id;
      data = await this.modelInstance.where(map).find();
      return this.success(data);
    }
    // 获取列表
    const type = this.get('type') || 'province'; // province,city,district
    // 归档
    if (type === 'province') {
      map['level'] = 1;
      map['upid'] = 0;
    }

    // 归档
    if (type === 'city') {
      const upid = this.get('upid') || 0;
      if (think.isEmpty(upid)) {
        return this.success(data);
      }

      map['level'] = 2;
      map['upid'] = upid;
    }
    // 归档
    if (type === 'district') {
      const upid = this.get('upid') || 0;
      if (think.isEmpty(upid)) {
        return this.success(data);
      }

      map['level'] = 3;
      map['upid'] = upid;
    }

    // 关键词
    const key = this.get('key');
    if (key) {
      map['name'] = ['like', '%' + key + '%'];
    }

    // 页码
    const page = this.get('page') || 0;

    if (page > 0) {
      // 每页显示数量
      const pageSize = this.get('pageSize') || 10;

      // think.logger.debug(map);

      data = await this.modelInstance.where(map).page(page, pageSize).order('id asc').countSelect();
      
      think.logger.debug(data);
      
      return this.success(data);
    } else {
      // 不分页
      data = await this.modelInstance.where(map).order('id asc').select();
      return this.success(data);
    }
  }

  /**
     * 删除内容
     * @return {[type]} [description]
     */
  async deleteAction() {
    if (!this.id) {
      return this.fail(1001, '记录不存在');
    }
    const rows = await this.modelInstance.where({
      id: this.id
    }).delete();
    if (rows) {
      // await this.hook('contentDelete', {id: this.id});
      return this.success({
        affectedRows: rows
      }, '删除成功');
    } else {
      return this.fail(1000, '删除失败');
    }
  }
};
